<?php

namespace app\common\model;

use app\common\cachemodel\Article;
use app\common\cachemodel\GoddessArea;
use app\common\cachemodel\ZlGoddessState;
use app\common\lib\Util;
use XznsTools\cache\CacheManage;

class ArticleCollect extends BaseCache
{
    protected $table = 'wechatadmin.system_article_collect';
    protected $cacheModel = 'user.collect';

    /**
     * 关联文章
     * @return \think\model\relation\belongsTo
     */
    public function article()
    {
        return $this->belongsTo('Article', 'id', 'aid');
    }

    /**
     * 获取用户所有收藏（分页）
     * @param int $uid
     * @param int $timeType 时间格式类型 1=>时间戳格式 2=>字符串格式
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getUserCollectPage(int $uid, $timeType = 2, int $limit = 10)
    {
        $page = input('page/d', 1);
        $ids = $this->getUserAllCollectFromCache($uid, 0);
        $ids = array_values($ids);
        $num = count($ids);
        $data_list = getPaginatorData($num, $page);
        //获取分页后的数据
        $ids = array_slice($ids, $data_list['start'], $limit);
        $data = $this->batchGetInfoByIds($ids, ['aid', 'type', 'create_time']);
        $data_list['data'] = $this->resetCollect($uid, $ids, $data, $timeType);
        unset($data_list['start'], $data_list['end']);
        return $data_list;
    }

    /**
     * 重组收藏列表数据
     * @param int $uid
     * @param array $ids
     * @param array $commentDatas
     * @param int $timeType 时间格式类型 1=>时间戳格式 2=>字符串格式
     * @return array
     * @throws \Exception
     */
    public function resetCollect(int $uid, array $ids, array $commentDatas, int $timeType = 1)
    {
        // 组合数据 并排序
        $resData = [];
        $GoddessStateModel = new ZlGoddessState();
        $GoddessAreaModel = new GoddessArea();
        $ArticleModel = new Article();
        foreach ($ids as $idItem)
        {
            $time = $timeType == 1 ? (int)$commentDatas[$idItem]['create_time'] : Util::timeToStr($commentDatas[$idItem]['create_time']);
            //类型 1=>星文，2=>女神动态，3=>女神专区
            switch ($commentDatas[$idItem]['type'])
            {
                case 1:
                    $article = current($ArticleModel->batchGetInfo([$commentDatas[$idItem]['aid']], ['id', 'title', 'introduction']));
                    $id = $article['id'] ?? 0;
                    $title = $article['title'] ?? '';
                    $introduction = $article['introduction'] ?? '';
                    break;
                case 2:
                    $article = $GoddessStateModel->getInfoById($commentDatas[$idItem]['aid'], ['id', 'title', 'introduction', 'type']);
                    $id = $article['id'];
                    $title = $article['title'];
                    $introduction = $article['introduction'];
                    $content_type = (int)$article['type'];
                    break;
                case 3:
                    $article = current($GoddessAreaModel->batchGetThemeInfo($commentDatas[$idItem]['aid'], ['id', 'title']));
                    $id = $article['id'];
                    $title = $article['title'];
                    break;
            }
            //旧版收藏数据格式
            if ($timeType == 1)
            {
                $arr = [
                    'id' => (int)($id ?? 0),
                    'title' => $title ?? '',
                    'introduction' => $introduction ?? '',
                    'create_time' => $time,
                ];
            } else//新版收藏数据格式
            {
                $arr = [
                    'id' => (int)$idItem,
                    'aid' => (int)($id ?? 0),
                    'title' => $title ?? '',
                    'introduction' => $introduction ?? '',
                    'time' => $time,
                    'type' => (int)$commentDatas[$idItem]['type'],
                    'content_type' => $content_type ?? 1
                ];
            }
            //过滤文章不存在的情况
            if (isset($id) && $id)
            {
                $resData[] = $arr;
            }
        }
        return $resData;
    }

    /**
     * 添加收藏
     * @param $uid
     * @param $aid
     * @param $type [1=>星文，2=>女神动态，3=>女神专区]
     * @return bool
     * @throws \Exception
     */
    public function saveData(int $uid, int $aid, int $type)
    {
        try
        {
            $id = $this->insertGetId(['aid' => $aid, 'uid' => $uid, 'type' => $type, 'create_time' => time()]);
        }
        catch (\Exception $e)
        {
            return false;
        }
        $this->listDataAdd($uid, [$aid => $id], 0);
        $this->listDataAdd($uid, [$aid => $id], $type);
        //获取对应的内容信息
        switch ($type)
        {
            case 1:
                $article = current((new \app\common\cachemodel\Article())->batchGetInfo([$aid], ['id', 'title']));
                break;
            case 2:
                $article = (new ZlGoddessState())->getInfoById($aid);
                break;
            case 3:
                $article = current((new GoddessArea())->batchGetThemeInfo([$aid], ['id']));
                break;
            default:
                $article = [];
                break;
        }
        if ($article)
        {
            $cacheKey = $type == 1 ? 'collect' : 'collect_num';
            //对应内容收藏数据自增 1
            (new \app\common\cachemodel\ArticleComment())->commentOrgoodAdd($type, $aid, $cacheKey, 1);
        }
        return true;
    }

    /**
     * 取消收藏
     * @param int $uid
     * @param int $type [1=>星文，2=>女神动态，3=>女神专区]
     * @param int $aid 收藏的内容id
     * @param int $id 收藏id
     * @return bool
     * @throws \Exception
     */
    public function delData(int $uid, int $type = 0, int $aid = 0, int $id = 0)
    {
        if ($id)
        {
            //获取收藏信息
            try
            {
                $data = $this->where(['id' => $id, 'uid' => $uid])->field('aid,type')->findOrFail()->toArray();
                $aid = $data['aid'];
                $type = $data['type'];
            }
            catch (\Exception $e)
            {
                $type = 0;
                $aid = 0;
            }
        }
        //获取对应的内容信息
        switch ($type)
        {
            case 1:
                $article = current((new \app\common\cachemodel\Article())->batchGetInfo([$aid], ['id', 'title']));
                break;
            case 2:
                $article = (new ZlGoddessState())->getInfoById($aid);
                break;
            case 3:
                $article = (new GoddessArea())->batchGetThemeInfo([$aid], ['id']);
                break;
            default:
                $article = [];
                break;
        }
        if ($article)
        {
            try
            {
                $this->where(['uid' => $uid, 'aid' => $aid])->delete();
            }
            catch (\Exception $e)
            {
                return false;
            }
            $this->listDataDel($uid, [$aid], 0);
            $this->listDataDel($uid, [$aid], $type);
            $cacheKey = $type == 1 ? 'collect' : 'collect_num';
            //对应内容收藏数据自增 -1
            (new \app\common\cachemodel\ArticleComment())->commentOrgoodAdd($type, $aid, $cacheKey, -1);
            return true;
        }
        return false;
    }

    /**
     * 缓存获取用户收藏
     * @param $uid
     * @param $type 0=>所有 1=>星文，2=>女神动态，3=>女神专区
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserAllCollectFromCache(int $uid, int $type)
    {
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setSort('desc')
            ->setListKeyType($type)
            ->ZsGetIocData('list', function () use ($type, $uid)
            {
                return $this->getUserAllCollectFromDms($type, $uid);
            }, true);
        return $data;
    }

    /**
     * 数据库获取用户收藏信息id
     * @param $type 0=>所有 1=>星文，2=>女神动态，3=>女神专区
     * @param $uid
     * @return array|\PDOStatement|string|\think\Model
     */
    public function getUserAllCollectFromDms(int $type, int $uid)
    {
        if ($type)
        {
            $where = ['uid' => $uid, 'type' => $type];
        } else
        {
            $where = ['uid' => $uid];
        }
        try
        {
            $aids = $this->where($where)->column('id', 'aid');
        }
        catch (\Exception $e)
        {
            $aids = [];
        }
        return $aids;
    }

    /**
     * 批量获取收藏
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|\PDOStatement|string|\think\Model|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        try
        {
            $data = $this->where(['id' => ['in', $ids]])->order('id', 'DESC')->column('aid,type,create_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}
